package com.mindmap.ui;

import com.mindmap.model.MindMap;
import com.mindmap.model.Node;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;

public class StructurePanel extends JPanel {
    private MainFrame mainFrame;
    private JTree tree;

    public StructurePanel(MainFrame mainFrame) {
        this.mainFrame = mainFrame;
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(300, 700));

        tree = new JTree();
        tree.setRootVisible(false);
        add(new JScrollPane(tree), BorderLayout.CENTER);
    }

    public void updateStructure(MindMap mindMap) {
        if (mindMap == null || mindMap.getRoot() == null) {
            tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
            return;
        }

        DefaultMutableTreeNode rootTreeNode = buildTreeNode(mindMap.getRoot());
        tree.setModel(new DefaultTreeModel(rootTreeNode));

        // 展开所有节点
        for (int i = 0; i < tree.getRowCount(); i++) {
            tree.expandRow(i);
        }
    }

    private DefaultMutableTreeNode buildTreeNode(Node node) {
        DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(node.getText());
        for (Node child : node.getChildren()) {
            treeNode.add(buildTreeNode(child));
        }
        return treeNode;
    }
}
